package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/*
* 鸿宇数智
* */
@Slf4j
public class Plugin_ECARD_P043 implements ChannelService {

    @Override
    public ChannelResult QueryBalance(JSONObject apiConfig) {
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }

    @Override
    public ChannelResult Submit(JSONObject apiConfig, Map<String, Object> data) {
        try {
            String accountVal = String.valueOf(data.get("AccountVal"));
            String channelOrderCode = String.valueOf(data.get("ChannelOrderCode"));
            String supProductId = String.valueOf(data.get("SUPProductId"));

            String submitUrl = apiConfig.getString("SubmitUrl");
            String appId = apiConfig.getString("AppId");
            String appSecret = apiConfig.getString("AppSecret");
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
            String formattedTimestamp = now.format(formatter);

            HashMap<String, String> submitParams = new HashMap<>();
            submitParams.put("outOrderId",channelOrderCode);//
            submitParams.put("appId",appId);
            submitParams.put("uuid",accountVal);//充值号码/帐号/卡号
            submitParams.put("itemId",supProductId);
            submitParams.put("timestamp",formattedTimestamp);
            submitParams.put("appSecret",appSecret);
            String sign = createLinkString(submitParams);
            submitParams.put("sign",sign);
            submitParams.remove("appSecret");

            String resStr = HttpTool.HttpPost(submitUrl, submitParams);
            JSONObject parseObject = JSONObject.parseObject(resStr);
            String code = parseObject.getString("code");
            String msg = parseObject.getString("msg");
            if (code.equals("00") ||code.equals("-16")){
                return ChannelResult.IN_PROCESS("充值中");
            }
            if (code.equals("-10")||code.equals("-13")||code.equals("-22")||code.equals("-23")||code.equals("-99")){
                return ChannelResult.error(msg);
            }
            return ChannelResult.FAILED(msg);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("鸿宇数智提交订单接口错误：",e);
            return  ChannelResult.error("鸿宇数智提交订单接口错误");
        }

    }


    @Override
    public ChannelResult Query(JSONObject apiConfig, Map<String, Object> data) {

        try {
            String channelOrderCode = String.valueOf(data.get("ChannelOrderCode"));

            String appId = apiConfig.getString("AppId");
            String appSecret = apiConfig.getString("AppSecret");
            String queryUrl = apiConfig.getString("QueryUrl");

            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
            String formattedTimestamp = now.format(formatter);

            HashMap<String, String> queryParams = new HashMap<>();
            queryParams.put("appId",appId);
            queryParams.put("outOrderId",channelOrderCode);
            queryParams.put("timestamp",formattedTimestamp);
            queryParams.put("appSecret",appSecret);
            String sign = createLinkString(queryParams);
            queryParams.put("sign",sign);
            queryParams.remove("appSecret");

            String resStr = HttpTool.HttpPost(queryUrl, queryParams);
            JSONObject parseObject = JSONObject.parseObject(resStr);
            String code = parseObject.getString("code");
            String msg = parseObject.getString("msg");
            if (code.equals("00")){
                String orderStatus = parseObject.getString("orderStatus");
                String orderDesc = parseObject.getString("orderDesc");
                if (orderStatus.equals("2")) {
                    return ChannelResult.success("充值成功");
                }
                if (orderStatus.equals("3")) {
                    return ChannelResult.FAILED(orderDesc);
                }
                if (orderStatus.equals("1")) {
                    return ChannelResult.IN_PROCESS("充值中");
                }
                return ChannelResult.error(orderDesc);
            }
            return ChannelResult.error(msg);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("鸿宇数智查询订单接口错误：",e);
            return  ChannelResult.error("鸿宇数智查询订单接口错误");
        }

    }

    @Override
    public ChannelResult Notify(JSONObject apiConfig, Map<String, Object> data) {
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");
    }

    public static String createLinkString(Map params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = (String) params.get(key);

            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }
        System.out.println("原串"+prestr);
        return  md5(prestr);
    }
    /**
     * MD5指纹算法
     *
     * @param str
     * @return
     */
    public static String md5(String str) {
        if (str == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(str.getBytes());
            return bytesToHexString(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将二进制转换成16进制
     * @param src
     * @return
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

}
